package exportimporterentities;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import org.apache.log4j.Logger;

import api.entitites.IGarage;
import api.entitites.IMaster;
import api.entitites.IOrder;
import api.messages.Messager;

public class Export {

	private Writer garageWriter;
	private Writer masterWriter;
	private Writer orderWriter;
	private static final String NEW_LINE = "\n";
	private static final String GARAGE_PATH_CSV="garage.csv";
	private static final String MASTER_PATH_CSV="master.csv";
	private static final String ORDER_PATH_CSV="order.csv";
	private Logger log = Logger.getLogger(Export.class);

	Export() {
		try {

			garageWriter = new FileWriter(GARAGE_PATH_CSV);
			masterWriter = new FileWriter(MASTER_PATH_CSV);
			orderWriter = new FileWriter(ORDER_PATH_CSV);
		} catch (IOException e) {
			System.out.println(Messager.UNSUCCESS_RESAVE_DATA);
			log.fatal(Messager.UNSUCCESS_RESAVE_DATA);
			
		}

	}

	void exportGarage(ArrayList<IGarage> garList) {
		try {
			for (IGarage gar : garList) {
				String s = gar.getId() + " " + gar.getNumberGarage();
				garageWriter.write(s);
				garageWriter.write(NEW_LINE);
			}
			garageWriter.close();
		} catch (IOException e) {
			log.fatal(Messager.UNSUCCESS_RESAVE_DATA);
			throw new RuntimeException(Messager.UNSUCCESS_RESAVE_DATA);
		}

	}

	void exportMaster(ArrayList<IMaster> masList) {
		try {
			for (IMaster mas : masList) {
				String s = mas.getId() + " " + mas.getNameMaster();
				masterWriter.write(s);
				masterWriter.write(NEW_LINE);
			}
			masterWriter.close();
		} catch (IOException e) {
			log.fatal(Messager.UNSUCCESS_RESAVE_DATA);
			throw new RuntimeException(Messager.UNSUCCESS_RESAVE_DATA);
		}

	}

	void exportOrder(ArrayList<IOrder> ordList) {

		try {
			SimpleDateFormat f = new SimpleDateFormat(Messager.DATE_FORMAT);
			for (IOrder ord : ordList) {
				String s = ord.getId() + " " + ord.getNumberOrder() + " "
						+ f.format(ord.getFillingDate().getTime()) + " "
						+ f.format(ord.getDeadlineDate().getTime()) + " "
						+ f.format(ord.getBeginingDate().getTime()) + " "
						+ ord.getPrice() + " " + ord.getOrderStatus() + " "
						+ ord.getMaster().getId() + " "
						+ ord.getGarage().getId();
				orderWriter.write(s);
				orderWriter.write(NEW_LINE);
			}
			orderWriter.close();
		} catch (IOException e) {
			log.fatal(Messager.UNSUCCESS_RESAVE_DATA);
			throw new RuntimeException(Messager.UNSUCCESS_RESAVE_DATA);
		}
	}

}
